package com.yuan.springcloud.common.config;

import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * MDC设置traceId拦截器
 * 用于记录日志时写入唯一请求标识
 *
 * @author china
 */
@Component
public class TraceIdInterceptor extends HandlerInterceptorAdapter {
    private static final String UNIQUE_ID = "TRACE_ID";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        MDC.put(UNIQUE_ID, UUID.randomUUID().toString());
        return true;
    }

	@Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        MDC.clear();
    }
}